<?php

class PubMed
{
    var $searchHost = "http://www.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?";
    var $fetchHost = "http://www.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?";
    var $docHost = "http://www.ncbi.nlm.nih.gov/m/pubmed/";
    var $webEnv = "WgHmIcDG]B";
    var $mode = "xml";
    var $db = "pubmed";
    var $usehistory = "y";
    var $mError = '';

    function _processCurl($url)
    {
	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_HEADER, 0);
        //curl_setopt($ch, CURLOPT_PROXY, "http://192.168.4.102:4044");
        //curl_setopt($ch, CURLOPT_PROXYPORT, 4044);
	$data = curl_exec($ch);
        curl_close($ch);
        $results = new SimpleXmlElement($data, LIBXML_NOCDATA);
	return $results;
    }

    public function DocSearch($term, $startFrom = 1, $recordCount = 50)
    {
        if('' == $term)
        {
            $this->mError = "No term specified";
            return false;
	}

        $searchUrl = $this->searchHost
                . "db=" . $this->db
                . "&term=" . $term
                . "&retstart=" . $startFrom
                . "&retmax=" . $recordCount
                . "&usehistory=" . $this->usehistory;

        $results = $this->_processCurl($searchUrl);

        return $results;
    }

    public function DocFetch($doc_ids)
    {
        if(!is_array($doc_ids) || count($doc_ids) < 1)
        {
            $this->mError = "No id specified";
            return false;
	}

        $fetchUrl = $this->fetchHost
                . "db=" . $this->db
                . "&WebEnv=" . $this->webEnv
                . "&mode=" . $this->mode;

        foreach ($doc_ids as $did)
        {
            $fetchUrl = $fetchUrl . "&id=" . $did;
        }

        $results = $this->_processCurl($fetchUrl);

        return $results;
    }

    function GetError()
    {
	return $this->mError;
    }
}
?>
